package com.pudu.mydemo.entity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.pudu.mydemo.Receiver.AlarmReceiver;
import com.pudu.mydemo.utils.RobotFileUtils;
import com.pudu.pdrobot.App;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;

import cz.msebera.android.httpclient.Header;

/**
 * Created by lgq on 2016/8/16.
 */
public class FileUpload {
    /**
     * 设置定时的小时为22点  分钟为0分
     */
    private static final int mHour = 22;
    private static final int mMinute = 0;

    private ArrayList<String> arrayList = new ArrayList<>();

    //只上传了当天的文件
    private String srcPath = "";
    //设置上传的url地址
    private static final String URLString ="http://120.24.19.24/LogUpload0.9L.php";


    /* 上传文件至Server，uploadUrl：接收文件的处理页面 */
    private AsyncHttpClient mAsyncHttpClient;

    public void uploadFile(Context context)
    {
        File file = new File(App.getInstance().getLogPath());
        File[] subFile = file.listFiles();
        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            if (!subFile[iFileLength].isDirectory()) {
                String absulotePath = subFile[iFileLength].getAbsolutePath();

                String strBakPathFile = RobotFileUtils.movePathFile(absulotePath, App.getInstance().getLogBakPath());

                if( strBakPathFile != null && strBakPathFile.isEmpty() == false) {
                    UploadMyFile(strBakPathFile, context);
                }
            }
        }
    }

    public void UploadMyFile(final String strPathFile,Context context)
    {
        File myfile = new File(strPathFile);

        mAsyncHttpClient = new AsyncHttpClient();
        mAsyncHttpClient.setTimeout(100 * 1000);

        RequestParams params = new RequestParams();
        final String contentType = "application/octet-stream";
        try {
            params.put("file", myfile, contentType);
            params.setHttpEntityIsRepeatable(true);
            params.setUseJsonStreamer(false);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ResponseHandlerInterface responseHandler = new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                String data = new String(responseBody);
                Log.i("FileUpload", "onSuccess:" + data);

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.i("FileUpload", "onFailure !");
            }
        };

        mAsyncHttpClient.post(context, URLString, params, responseHandler);
    }

    /**
     * 直接设置某个时间点执行的事件
     */
    public void onTimePost(Context mContext){
        Intent intent = new Intent(mContext, AlarmReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        long systemTime = System.currentTimeMillis();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
// 这里时区需要设置一下，不然会有8个小时的时间差
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        calendar.set(Calendar.MINUTE, mMinute);//mMinute=0
        calendar.set(Calendar.HOUR_OF_DAY, mHour); //mHour=22
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
// 选择的定时时间
        long selectTime = calendar.getTimeInMillis();
        Log.i("LogPrint","selectTime:"+selectTime);
// 如果当前时间大于设置的时间，那么就从第二天的设定时间开始
        if(systemTime > selectTime) {
            Log.i("FileUpload","设置的时间小于当前时间");
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            selectTime = calendar.getTimeInMillis();
        }
// 计算现在时间到设定时间的时间差
        long time = selectTime - systemTime;

// 进行闹铃注册
        AlarmManager manager = (AlarmManager)mContext.getSystemService(mContext.ALARM_SERVICE);
        //设置重复闹钟
        manager.setRepeating(AlarmManager.RTC_WAKEUP,selectTime,
                (24*60*60*1000), sender);
        Log.i("LogPrint","time ==== " + time +", selectTime ===== "
                + selectTime + ", systemTime ==== " + systemTime);
    }
}
